package com.qianbei.user.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.qianbei.R;
import com.qianbei.common.base.BaseFragment;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.ConstantValue;
import com.qianbei.common.utilis.Util;
import com.qianbei.user.ChangePwdActivity;
import com.qianbei.user.FindPasswdActivity;
import com.qianbei.user.model.UserMode;
import com.qianbei.user.regist.RegisterActivity;
import com.qianbei.view.HomeActivity;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;


public class LoginFragment extends BaseFragment {
    private TextView btn_register;
    private TextView mCountryNumberTv;
    private EditText et_mobile, et_password;
    private String str_mobile, str_password, userID;
    private boolean isAutoLogin;

    private Activity context;
    private String target;
    private String mWeChatInfo;
    private String[] mWeChatArray;

    private String mCountryCode = "86";
    private String mCountryName = "中国";

    //登录回调 如果监听登录 添加一个 观察者 ,等待登录成功通知
    public static ArrayList<LoginCall> loginCalls = new ArrayList<LoginCall>();
    private Button mBtnRegister2;
    int mVersionCode = 0;
    String mVersionName;
    private ProgressDialog progressDialog;

    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);

        if (args != null) {
            mWeChatInfo = args.getString(ConstantValue.WE_CHAT_INFO_KEY);
            if (!TextUtils.isEmpty(mWeChatInfo)) {
                mWeChatArray = mWeChatInfo.split("/@:/");
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.user_login, null);
        target = getActivity().getIntent().getStringExtra("targetClass");

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        initWidget(getView());
    }

    @SuppressLint("NewApi")
    private void initWidget(View v) {
        mCountryNumberTv = (TextView) v.findViewById(R.id.tv_country_number);
        et_mobile = (EditText) v.findViewById(R.id.et_mobile);

        if (!TextUtils.isEmpty(SetData.getUserPhone())) {
            et_mobile.setText(SetData.getUserPhone());
        }
        et_password = (EditText) v.findViewById(R.id.et_password);
        if (!TextUtils.isEmpty(SetData.getPass())) {
            et_password.setText(SetData.getPass());
        }
        mBtnRegister2 = (Button) v.findViewById(R.id.btn_register_2);
        v.findViewById(R.id.btn_login_2).setOnClickListener(this);
        btn_register = (TextView) v.findViewById(R.id.btn_register);
        v.findViewById(R.id.user_login_fogetpass).setOnClickListener(this);
        v.findViewById(R.id.user_login_change_bt).setOnClickListener(this);
        mCountryNumberTv.setOnClickListener(this);
        mBtnRegister2.setOnClickListener(this);
        if (mWeChatArray != null && mWeChatArray.length == 7) {
            et_mobile.setText(mWeChatArray[6]);
        }

        try {
            PackageInfo packageInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            mVersionCode = packageInfo.versionCode;
            mVersionName = packageInfo.versionName;
            TextView viewById = (TextView) v.findViewById(R.id.tv_versionCode);
            viewById.setText("v" + mVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        et_password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if ((i == EditorInfo.IME_ACTION_DONE) ||
                        (keyEvent != null && KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode() && KeyEvent.ACTION_DOWN == keyEvent.getAction())) {
//                    Util.hideSoftInputFromWindow();

                    String msg = checkUserInputValues();
                    if (!"0".equals(msg)) {
                        new MsgAlert().show(msg);
                    } else {
                        doLogin(str_mobile, str_password);
                    }
                }
                return false;
            }
        });

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_register_2:
                mContext.startActivity(new Intent(mContext,
                        RegisterActivity.class));
                break;
            case R.id.user_login_fogetpass:
                mContext.startActivity(new Intent(mContext,
                        FindPasswdActivity.class));
                break;
            case R.id.user_login_change_bt://修改密码
                mContext.startActivity(new Intent(mContext,
                        ChangePwdActivity.class));
                break;
            case R.id.btn_login_2:
                Util.hideSoftInputFromWindow(v);
                String msg = checkUserInputValues();
                if (!"0".equals(msg)) {
                    new MsgAlert().show(msg);
                    return;
                } else {
                    progressDialog = new ProgressDialog(mContext);
                    progressDialog.showProgress("正在登录");
                    doLogin(str_mobile, str_password);
                }
                break;
            case R.id.tv_country_number:
                startActivityForResult(new Intent(getActivity(), CountryCodeActivity.class), 1);
                break;
            default:
                break;
        }
    }

    /**
     * 用户登陆
     */
    private void doLogin(final String username, final String password) {
        String url = ServerControl.URL + ServerControl.url_p_login;
        JSONObject obj = new JSONObject();
        try {
            obj.put("username", username);
            obj.put("password", password);
        } catch (JSONException e) {
        }
        ServerControl sc = new ServerControl(Request.Method.POST,
                url, obj);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                Log.d("修改密码", password+"登录返回" + sr.toString());
                if (sr.isContinue) {
                    //boolean setMoreThan90 = body.optBoolean("setMoreThan90");
                    go2Home(sr);
                }
                progressDialog.hide();
            }
        };
        sc.startVolley();
    }

    private void go2Home(ServerResult result) {
        JSONObject body = result.bodyData.optJSONObject("data");
        UserMode mode = new UserMode();
        mode.phone_number = str_mobile;//账号
        mode.password = str_password;//密码

        mode.user_id = body.optString("userId");
        mode.role = body.optString("role");

        SetData.setUserID(mode.user_id);
        SetData.setPass(mode.password);
        SetData.setUserPhone(mode.phone_number);
        SetData.setUserRole(mode.role);

        SetData.setUSER(str_mobile);
        SetData.setPSW(str_password);
        SetData.setToken(body.optString("token"));
        SetData.setMoreThan90(body.optBoolean("setMoreThan90"));

        startActivity(new Intent(mContext, HomeActivity.class));
        getActivity().finish();
    }

    private String checkUserInputValues() {
        str_mobile = et_mobile.getText().toString();
        /** 电话号码验证 */
        if (str_mobile == null || "".equals(str_mobile)) {
            return "账号为空";
        }

        str_password = et_password.getText().toString();

        if (str_password == null || "".equals(str_password)) {
            return getString(R.string.menu_login_activity_check_password1);
        }
        if (str_password.length() < 6 || str_password.length() > 16) {
            return getString(R.string.menu_register_activity_check_password_length_min);
        }
//        String regex = "[A-Za-z0-9`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& ;*（）——+|{}【】‘；：”“’。，、？]+";
//        if (!str_password.matches(regex)) {
//            return getString(R.string.menu_register_activity_check_password_regex);
//        }

        return "0";
    }


    /**
     * 添加观察者
     */
    public static void addCall(LoginCall call) {
        loginCalls.add(call);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (mContext.RESULT_OK == resultCode && data != null) {
            mCountryCode = data.getStringExtra(ConstantValue.COUNTRY_CODE_KEY);
            mCountryName = data.getStringExtra(ConstantValue.COUNTRY_NAME_KEY);
            mCountryNumberTv.setText(getString(R.string.country_code_format, mCountryName, mCountryCode));
        }
    }
}